<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Services\UploadService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;

class BuyHelpBannerController extends Controller
{
    /**
     * 编辑展示页面
     * @name edit
     * @param \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 9:43
     */
    public function index(){
        $data = Banner::where('origin',Banner::BuyHelpBanner)->orderBy('sort','desc')->first();
        return view('Admin.buyHelpBanner.edit',['data' => $data]);
    }

    /**
     * 编辑AJAX保存操作
     * @name update
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 10:11
     */
    public function update(Request $request,$id){
        DB::beginTransaction();

        try{
            $model = Banner::findOrFail($id);

            $UploadService = new UploadService($request,'buyHelpBanner','photo','oss');
            $uploadresult = $UploadService->upload();
            if($uploadresult['status'] == UploadService::FailStatus){
                throw new \Exception($uploadresult->message ?? '图片上传失败');
            }
            $model->photo = $uploadresult['url'];
            $model->save();

        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );

        }
        DB::commit();
        return $this->getResponse('保存成功');
    }
}
